<?php

namespace app\common\model;

use think\facade\Db;
use think\Model;

class Post extends Model
{
    protected $json = ['media'];
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    public function userInfo()
    {
        return $this->hasOne("User", "uid", "uid");
    }

    public function discuss()
    {
        return $this->hasOne("Discuss", "id", "discuss_id");
    }

    public function topicInfo()
    {
        return $this->hasOne("Topic", "id", "topic_id");
    }

    public static function getList($where = "", $order = "id desc", $paginate = 10,$uid = 0)
    {
        $list = self::withJoin(['userInfo','topicInfo'])->where($where)->order($order)->paginate($paginate)->each(function ($item) use ($uid) {
            $item["comment_count"] = Db::name("comment")->where("post_id", $item["id"])->count();
            $item["fabulous_count"] = Db::name("post_fabulous")->where("post_id", $item["id"])->count();
            $item["collection_count"] = Db::name("post_collection")->where("post_id", $item["id"])->count();

            if ($item["discuss_id"] > 0) {
                $item["discuss_title"] = Db::name("discuss")->where("id", $item["discuss_id"])->value("title");
            }

            if($item["vote_id"] > 0){
                $vote = Db::name("vote_subject")->where("id",$item["vote_id"])->find();
                $vote["options"] = Db::name("vote_option")->where("vote_id",$vote["id"])->select();
                $item["vote_info"] = $vote;
            }

            //是否收藏
            $item["is_collection"] = false;
            $isCollection = Db::name("post_collection")->where(["uid" => $uid, "post_id" => $item["id"]])->find();

            if ($isCollection) {
                $item["is_collection"] = true;
            }

            //最新三条评论
            $item["comment_list"] = Comment::withJoin(["userInfo"])->where(["post_id" => $item["id"],"pid" => 0])->limit(3)->select();
            return $item;
        });
        return $list;
    }
}